import React, { Component } from 'react'

import { Modal, Icon } from 'antd';
import { ClickLink } from '../../styled/list';

import styles from './style.less'

interface IProps {
  hasText?: string,
  missText?: string,
  url: string,
  isThumb?: boolean,
  thumbWidth?: string,
  icon?: boolean,
  thumbHeight?: string,
  margin?: string,
}

export default class Imgviewer extends Component<IProps> {

  state = {
    imgVisible: false,
    url: this.props.url
  }

  static getDerivedStateFromProps(props, state) {
    if (props.url !== state.url) {
      return {
        url: props.url
      }
    }

    return null;
  }

  handleCancel = () => {
    this.setState({
      imgVisible: false
    })
  }

  handleShow = () => {
    this.setState({
      imgVisible: true
    })
  }

  render() {

    const { imgVisible, url } = this.state;
    const { isThumb = false, thumbWidth = '30px', thumbHeight = '30px', margin = '0px', icon = true } = this.props;

    return (
      <>
        {url ?
          (isThumb ? (
            <section style={{ width: thumbWidth, height: thumbHeight, overflow: 'hidden', margin: margin, background: '#ccc' }}>
              <img 
                alt="查看图片" 
                onClick={this.handleShow} 
                style={{ 
                  width: thumbWidth, transform: 'translate(-50%, -50%)', 
                  top: '50%', left: '50%',
                  objectFit: 'contain', position: 'relative'
                }} 
                src={url} 
              />
            </section>
          )
            : <ClickLink onClick={this.handleShow}>
              {icon && <Icon type="picture" style={{marginRight: 10}}/>} 
              {this.props.hasText || '查看图片'}</ClickLink>)
          : <span style={{ paddingLeft: '20px' }}>{this.props.missText}</span>
        }
        <Modal title="查看图片" className={styles.showImgs} visible={imgVisible} footer={null} onCancel={this.handleCancel}>
          {url ? <img alt="查看图片" style={{ width: '100%' }} src={url} /> : null}
        </Modal>
      </>
    )
  }
}
